<template>
  <div class="common-layout">
    <el-container>
      <el-header style="background-color: #fff; height: 180px">
        <div
          class="common-layout-header"
          style="display: flex; flex-direction: column; align-items: flex-start"
        >
          <div class="common-layout-header-title">
            <img src="@/assets/img/列表.png" alt="" />作业管理
          </div>
          <div style="margin-top: 20px">
            <button @click="xuanze" class="orange-button">选择班级</button>
            <div style="display: flex; align-items: center">
              <div class="date-input" style="margin-right: 20px">
                日期：
                <el-date-picker
                  v-model="selectedDate"
                  value-format="YYYY-MM-DD"
                  type="date"
                  @change="handleDateChange"
                  :cell-class-name="cellClassName"
                >
                  <template #default="cell">
                    <div class="cell" :class="{ current: cell.isCurrent }">
                      <span class="text">{{ cell.text }}</span>
                      <span v-if="isHoliday(cell)" class="holiday" />
                    </div>
                  </template>
                </el-date-picker>
              </div>
              <div
                class="class-info"
                style="display: flex; align-items: center; margin-right: 20px"
              >
                <template v-if="chapterName && sectionName.length > 0">
                  <span style="margin-right: 10px"
                    >章节：<span style="color: #409eff">{{
                      chapterName
                    }}</span></span
                  >
                  <span style="margin-right: 10px">小节：</span>
                  <el-select v-model="table.taskId" placeholder="请选择小节">
                    <el-option
                      v-for="section in sectionName"
                      :key="section.value"
                      :label="section.label"
                      :value="section.value"
                    />
                  </el-select>
                </template>
                <template v-else>
                  <span>该天没有作业</span>
                </template>
              </div>
            </div>
            <div
              class="student-stats"
              v-if="chapterName && sectionName.length > 0"
            >
              <div style="margin-top: 5px">
                <span>班级人数：{{ totalStudents }}</span> &nbsp;
                <span>已交人数：{{ submittedStudents }}</span>
              </div>
              <button
                class="orange-button"
                @click="showUnsubmittedDialog = true"
                v-b-tooltip.hover
                title="点击显示未提交的名单"
              >
                未交人数：{{ unsubmittedStudents }}
              </button>
            </div>
          </div>
        </div>
      </el-header>
      <el-main class="common-layout-main" style="width: 100%">
        <el-table
          :data="filteredTaskList"
          border
          style="width: 100%"
          :header-cell-style="{
            textAlign: 'center',
            backgroundColor: '#f0f9eb',
            padding: '8px',
          }"
          :cell-style="{ textAlign: 'center', padding: '8px' }"
        >
          <!-- 姓名列 -->
          <el-table-column prop="nickName" label="姓名" />
          <!-- 作业评分列 -->
          <el-table-column prop="score" label="作业评分" />
          <!-- 评语列，支持文本溢出显示 -->
          <el-table-column
            prop="comment"
            label="评语"
            show-overflow-tooltip
            width="650"
          />
          <!-- 批改状态列 -->
          <el-table-column prop="approvalStatus" label="批改状态">
            <template #default="scope">
              <span :style="{ color: opt[scope.row.approvalStatus].color }">
                {{ opt[scope.row.approvalStatus].icon }}
                {{ opt[scope.row.approvalStatus].label }}
              </span>
            </template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column prop="operate" label="操作">
            <template #default="scope">
              <el-button
                @click="correct(scope.row.id)"
                type="primary"
                link
                icon="Edit"
                style="padding: 6px 12px; border-radius: 4px"
              >
                批改作业
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
    <!-- 未提交作业的学生 -->
    <el-dialog
      title="未提交作业名单"
      v-model="showUnsubmittedDialog"
      width="50%"
      custom-class="custom-dialog"
    >
      <el-table :data="unsubmittedStudents01" style="width: 100%" stripe border>
        <el-table-column prop="nickName" label="姓名"></el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="showUnsubmittedDialog = false"
            >关闭</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 新增的弹框 -->
    <el-dialog
      title="选择班级"
      v-model="showSelectDialog"
      width="30%"
      custom-class="custom-dialog"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <div class="dialog-content">
        <el-select
          v-model="classId"
          placeholder="请选择班级"
          style="width: 100%; margin-bottom: 20px"
          clearable
        >
          <el-option
            v-for="option in options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSelectDialog = false">取消</el-button>
          <el-button type="primary" @click="classopen">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage } from "element-plus"; // 如果需要使用 Element Plus 的消息提示
import route from "@/router";
import dayjs from "dayjs";
import {
  homework,
  two,
  findClassroomByTeacherId,
  selectTimeById,
} from "@/api/teacher/homework.js";
//缓存
import { mapState, mapActions } from "pinia";
import { useTokenStore1 } from "@/stores/classStore.js";
const classStore = useTokenStore1();

import { useUserInfoStore } from "@/store/user.js";

//获取用户状态
const userInfoStore = useUserInfoStore();

// 批改 状态
const opt = ref({
  0: { label: "已批改", color: "green", icon: "✅" }, // 已批改状态
  1: { label: "未批改", color: "red", icon: "❌" }, // 未批改状态
});

// 班级id
const classId = ref({});

// 下拉框选项 选择班级
const showSelectDialog = ref(false);
const options = ref([]);

// 章节名称
const chapterName = ref();

// 小节名称
const sectionName = ref([]);

// 数据内容  每个人
const taskList = ref([]);

// 获取当前时间 日期选择器
const selectedDate = ref(new Date().toISOString().split("T")[0]);

//有值的数组
const holidays = ref([]);
// 查询每一天是否有值
const fetchDaysWithValues = async () => {
  let res = await selectTimeById(taskUser01.value.userId);
  holidays.value = res.data; // 直接赋值日期数组
};
const isHoliday = (cell) => {
  const cellDate = dayjs(cell.date).format("YYYY-MM-DD");
  return holidays.value.includes(cellDate);
};
const cellClassName = ({ date }) => {
  const formattedDate = dayjs(date).format("YYYY-MM-DD");
  if (holidays.value.includes(formattedDate)) {
    return "holiday-cell";
  }
};

// 从 sessionStorage 中读取之前选择的日期
    const savedDate = sessionStorage.getItem('selectedDate');
    if (savedDate) {
      selectedDate.value = savedDate;
    }


// 控制弹框显示与隐藏的状态变量
const showUnsubmittedDialog = ref(false);

// 计算属性，用于获取未提交作业的学生列表
const unsubmittedStudents01 = computed(() => {
  return Array.isArray(taskList.value)
    ? taskList.value.filter((task) => task.commit === null)
    : [];
});

// 计算属性，用于过滤掉未提交作业的学生列表
const filteredTaskList = computed(() => {
  return Array.isArray(taskList.value)
    ? taskList.value.filter((task) => task.commit === 0)
    : [];
});

// 总人数
const totalStudents = computed(() =>
  Array.isArray(taskList.value) ? taskList.value.length : 0
);

// 已交作业的人数
const submittedStudents = computed(() => {
  return Array.isArray(taskList.value)
    ? taskList.value.filter((task) => task.commit === 0).length
    : 0;
});

// 未交作业的人数
const unsubmittedStudents = computed(() => {
  return Array.isArray(taskList.value)
    ? taskList.value.filter((task) => task.commit === null).length
    : 0;
});

// 查询数据
const taskUser01 = ref({
  userId: userInfoStore.userInfo.userId, // 用户ID
  submitTime: selectedDate.value, // 提交时间
});

// 查询表单
const home = async (table) => {
  let shuju = await homework({ ...table.value }); // 使用解构赋值确保发送正确的对象
  taskList.value = shuju.data.data;
};

// 查询 章节 小节
const two01 = async (taskUser01) => {
  let res = await two({ ...taskUser01.value }); // 使用解构赋值确保发送正确的对象
  // 章节
  chapterName.value = res.data.chapterName;
  //小节
  sectionName.value = res.data.sectionName.map((item) => ({
    value: item.section_id, // 假设每个小节有一个唯一的 ID
    label: item.section_name,
  }));
  // 设置默认选中第一个小节
  if (sectionName.value.length > 0) {
    table.value.taskId = sectionName.value[0].value;
  }
};

// 选择时间 查询 章节 小节
const handleDateChange = (value) => {
  taskUser01.value.submitTime = selectedDate.value;
  two01(taskUser01);
  table.value = {};
  taskList.value = [];
  table.value.classId = parseInt(classId.value); // 确保 classId 是整数
  home(table);
  // 保存选中的日期
  if (value) {
        sessionStorage.setItem('selectedDate', value);
      } else {
        sessionStorage.removeItem('selectedDate');
      }
};

// 选择框的值
const table = ref({
  taskId: "",
  userId: "",
  classId: "",
});

// 监听 selectedSection 变化  值一改变就走查询
watch(
  () => table.value.taskId,
  async (newVal) => {
    if (newVal) {
      taskList.value = [];
      table.value.taskId = newVal;
      table.value.userId = userInfoStore.userInfo.userId; // 用户ID
      home(table);
    }
  }
);

//获取登陆人的iD
const id = userInfoStore.userInfo.userId;

//查询班级
const classroom = async (id) => {
  let res = await findClassroomByTeacherId(id);
  options.value = res.data.map((item) => ({
    value: item.class_id,
    label: item.class_name,
  }));
};

const classopen = () => {
  //关闭弹框
  showSelectDialog.value = false;
  // 查询 章节小节
  two01(taskUser01);
  table.value.classId = parseInt(classId.value); // 确保 classId 是整数
  // 调用 setToken1 方法并传递 classId 参数
  classStore.setToken1(table.value.classId);
  home(table);
};

//选择班级
const xuanze = () => {
  classroom(id);
  showSelectDialog.value = true;
};

onMounted(() => {
  // 查询班级
  classroom(id);

  // 查询时间
  fetchDaysWithValues();

  //查询 班级id 查询过的  放在了 token里面   如果里面id没有值 则 显示弹框 选择班级查询
  if (
    // 判断 token 里面的值是否为空
    classStore.classId != null &&
    classStore.classId != "" &&
    classStore.classId != undefined
  ) {
    // 获取 token 里面的值
    classId.value = classStore.classId;
    // 查询 章节小节
    two01(taskUser01);
    // 调用 setToken1 方法并传递 classId 参数
    table.value.classId = parseInt(classId.value); // 确保 classId 是整数
    // 查询数据
    home(table);
  } else {
    // 查询班级
    classroom(id);
    // 显示弹框
    showSelectDialog.value = true;
  }
});

// 批改作业的方法
const correct = (id) => {
  // 实现批改作业的逻辑
  route.push("/class/CorrectingWork?id=" + id);
};
</script>

<style lang="scss" scoped>
/* 添加一些样式以美化日期选择器 */
input[type="date"] {
  padding: 8px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.common-layout-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.common-layout-header-title {
  font-size: 20px;
  display: flex;
  font-family: "微软雅黑";
  align-items: center;

  img {
    width: 30px;
  }
}

.common-layout-header-button {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-input {
  margin-bottom: 10px;
}

.class-info {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;

  span {
    margin-right: 10px;
  }
}

.el-select {
  width: 200px;
  margin-right: 20px;
}

.student-stats {
  display: flex;
  gap: 10px;
}

.clickable {
  cursor: pointer;
  color: #409eff;
  text-decoration: underline;

  &:hover {
    color: #66b1ff;
  }
}

.custom-dialog {
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-top: 20px;

  th {
    background-color: #f5f7fa;
  }

  td {
    padding: 12px 0;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.orange-button {
  background-color: orange;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;

  &:hover {
    background-color: rgb(255, 187, 0); /* 鼠标悬停时背景颜色变深 */
  }

  &:active {
    background-color: rgba(255, 68, 0, 0.582); /* 点击时背景颜色更深 */
    transform: scale(0.98); /* 点击时按钮稍微缩小 */
  }
}

.demo-date-picker {
  display: flex;
  justify-content: space-between;
}

.cell {
  height: 30px;
  padding: 3px 0;
  box-sizing: border-box;

  .text {
    width: 24px;
    height: 24px;
    display: block;
    margin: 0 auto;
    line-height: 24px;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    border-radius: 50%;
  }

  &.current .text {
    background: #626aef;
    color: #fff;
  }

  .holiday {
    position: absolute;
    width: 6px;
    height: 6px;
    background: orange;
    border-radius: 50%;
    bottom: 0px;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>
